import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/services.dart';
import 'package:grint/entity/comment.dart';
import 'package:grint/entity/content_submission.dart';
import 'package:grint/entity/user.dart';
import 'package:grint/entity/chat_message.dart';
import 'package:grint/utils/local_store.dart';
import 'package:grint/data/content_repository.dart';
import 'package:grint/data/chat_data.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

class DataInit {
  static final DataInit _instance = DataInit._internal();

  factory DataInit() {
    return _instance;
  }

  DataInit._internal();

  Future<void> initData() async {
    final localStore = LocalStore();

    bool hasInitialized = localStore.getFlagValue(
      'has_initialized',
      defaultValue: false,
    );

    // 检查是否需要重新初始化（用于修复缩略图问题）
    bool needsReinit = localStore.getFlagValue(
      'needs_thumbnail_fix',
      defaultValue: true,
    );

    if (hasInitialized && !needsReinit) return;

    await _initUserData();
    await _initFollowData();
    await _initContentData();
    await _initChatData();

    await localStore.setFlagValue('has_initialized', true);
    await localStore.setFlagValue('needs_thumbnail_fix', false);
  }

  /// 初始化用户数据
  Future<void> _initUserData() async {
    final localStore = LocalStore();

    final List<User> users = [
      User(
        id: '1001',
        username: 'user007',
        password: '123456',
        name: 'Johnson',
        avatar: 'assets/images/avatar-one.png',
        description: 'UI/UX designer with 5 years experience',
      ),
      User(
        id: '1002',
        username: 'user002',
        password: '123456',
        name: 'Emma',
        avatar: 'assets/images/avatar-two.png',
        description: 'Frontend developer passionate about React and Flutter',
      ),
      User(
        id: '1003',
        username: 'user003',
        password: '123456',
        name: 'Michael Chen',
        avatar: 'assets/images/avatar-three.png',
        description: 'Software engineer specializing in mobile applications',
      ),
      User(
        id: '1004',
        username: 'user004',
        password: '123456',
        name: 'John',
        avatar: 'assets/images/avatar-four.png',
        description: 'Software engineer specializing in mobile applications',
      ),
      User(
        id: '1005',
        username: 'user005',
        password: '123456',
        name: 'Lily',
        avatar: 'assets/images/avatar-five.png',
        description: 'Software engineer specializing in mobile applications',
      ),
      User(
        id: '1006',
        username: 'user006',
        password: '123456',
        name: 'Tom',
        avatar: 'assets/images/avatar-six.png',
        description: 'Software engineer specializing in mobile applications',
      ),
      User(
        id: '1007',
        username: 'user009',
        password: '123456',
        name: 'Doe',
        avatar: 'assets/images/avatar-seven.png',
        description: 'Software engineer specializing in mobile applications',
      ),
      User(
        id: '1008',
        username: 'user008',
        password: '123456',
        name: 'Jane',
        avatar: 'assets/images/avatar-eight.png',
        description: 'Software engineer specializing in mobile applications',
      ),
    ];

    final List<Map<String, dynamic>> usersJson =
        users.map((u) => u.toJson()).toList();
    final String usersJsonString = jsonEncode(usersJson);

    await localStore.setTextValue('users_data', usersJsonString);

    for (var user in users) {
      await localStore.setObjectValue('user_${user.id}', user.toJson());
    }
  }

  /// 初始化关注数据
  Future<void> _initFollowData() async {
    final localStore = LocalStore();

    // 为用户 1001 (Johnson) 设置默认关注列表
    final List<String> defaultFollowingUsers = [
      '1002', // Emma - Frontend developer
      '1003', // Michael Chen - Software engineer
      '1005', // Lily - Product manager
      '1006', // Tom - Backend developer
      '1008', // Jane - Software engineer
    ];

    // 保存关注数据到本地存储
    // 注意：这里使用的键名要与 FollowCubit 中的 _followingKey 一致
    await localStore.setTextValue(
      'following_users',
      jsonEncode(defaultFollowingUsers),
    );

    print('=== 默认关注数据初始化完成 ===');
    print('用户 1001 (Johnson) 默认关注了 ${defaultFollowingUsers.length} 个用户:');
    for (String userId in defaultFollowingUsers) {
      final userName = _getUserNameById(userId);
      print('  - $userId: $userName');
    }
  }

  /// 根据用户ID获取用户名（辅助方法）
  String _getUserNameById(String userId) {
    final userMap = {
      '1001': 'Johnson',
      '1002': 'Emma',
      '1003': 'Michael Chen',
      '1004': 'John',
      '1005': 'Lily',
      '1006': 'Tom',
      '1007': 'Doe',
      '1008': 'Jane',
    };
    return userMap[userId] ?? 'Unknown User';
  }

  /// 初始化内容数据
  Future<void> _initContentData() async {
    final contentRepository = ContentRepository();
    await contentRepository.initializeChallengeTasks();
    await _initDefaultShares();
    await _initCommentsData();
  }

  /// 初始化默认分享数据
  Future<void> _initDefaultShares() async {
    final contentRepository = ContentRepository();
    final random = Random();

    // 分享描述模板
    final List<String> challengeDescriptions = [
      'Just completed my daily brushing challenge! 🦷✨',
      'Challenge accepted: 2 minutes of perfect brushing! 💪',
      'Dental hygiene challenge conquered! 🏆',
      'Another day, another step towards healthier teeth!',
      'Feeling confident with my oral care routine 😊',
      'Brushing challenge mode: ON! Who\'s joining me?',
      'Consistency is key for dental health! 🎯',
      'This oral care challenge is making a difference!',
      'Protecting my smile, one brush at a time 🦷',
      'Daily dental care challenge completed! ✅',
    ];

    final List<String> dailyDescriptions = [
      'Starting my day with proper oral care! ☀️🦷',
      'Sharing my dental health journey with you all!',
      'Small habits, big impact on dental health 💫',
      'Grateful for my healthy smile today 🙏😊',
      'Taking care of my teeth, one day at a time',
      'Spreading awareness about oral health! 🦷✨',
      'Today\'s mood: confident smile! 😁',
      'Finding joy in maintaining good dental hygiene',
      'Sharing some oral health inspiration! 💪',
      'Healthy teeth, happy life! 🦷❤️',
      'My dental care routine is paying off! ✨',
      'Protecting my smile with good habits 😊',
    ];

    final List<ContentSubmission> defaultShares = [];

    // 预定义所有分享的配置，直观明确
    final List<Map<String, dynamic>> shareConfigs = [
      // Challenge Share 分享 (13个)
      {
        'id': 'challenge_share_1',
        'category': SubmissionCategory.challengeShare,
        'description': challengeDescriptions[0],
        'images': ['assets/images/share1.png', 'assets/images/eat1.png'],
        'isVideo': true,
        'videoIndex': 1,
      },
      {
        'id': 'challenge_share_2',
        'category': SubmissionCategory.challengeShare,
        'description': challengeDescriptions[1],
        'images': ['assets/images/share3.png'],
        'isVideo': true,
        'videoIndex': 2,
      },
      {
        'id': 'challenge_share_3',
        'category': SubmissionCategory.challengeShare,
        'description': challengeDescriptions[2],
        'images': [
          'assets/images/share4.png',
          'assets/images/eat5.png',
          'assets/images/share6.png',
        ],
        'isVideo': false,
      },
      {
        'id': 'challenge_share_4',
        'category': SubmissionCategory.challengeShare,
        'description': challengeDescriptions[3],
        'images': ['assets/images/share7.png'],
        'isVideo': false,
      },
      {
        'id': 'challenge_share_5',
        'category': SubmissionCategory.challengeShare,
        'description': challengeDescriptions[4],
        'images': ['assets/images/share8.png', 'assets/images/share9.png'],
        'isVideo': false,
      },
      {
        'id': 'challenge_share_6',
        'category': SubmissionCategory.challengeShare,
        'description': challengeDescriptions[5],
        'images': ['assets/images/share10.png'],
        'isVideo': false,
      },
      {
        'id': 'challenge_share_7',
        'category': SubmissionCategory.challengeShare,
        'description': challengeDescriptions[6],
        'images': ['assets/images/share11.png', 'assets/images/share12.png'],
        'isVideo': false,
      },
      {
        'id': 'challenge_share_8',
        'category': SubmissionCategory.challengeShare,
        'description': challengeDescriptions[7],
        'images': ['assets/images/share13.png'],
        'isVideo': false,
      },

      // Daily Share 分享 (11个)
      {
        'id': 'daily_share_1',
        'category': SubmissionCategory.dailyShare,
        'description': dailyDescriptions[0],
        'images': ['assets/images/share2.png', 'assets/images/eat2.png'],
        'isVideo': true,
        'videoIndex': 3,
      },
      {
        'id': 'daily_share_2',
        'category': SubmissionCategory.dailyShare,
        'description': dailyDescriptions[1],
        'images': ['assets/images/eat3.png'],
        'isVideo': true,
        'videoIndex': 4,
      },
      {
        'id': 'daily_share_3',
        'category': SubmissionCategory.dailyShare,
        'description': dailyDescriptions[2],
        'images': [
          'assets/images/eat4.png',
          'assets/images/share5.png',
          'assets/images/eat6.png',
        ],
        'isVideo': false,
      },
      {
        'id': 'daily_share_4',
        'category': SubmissionCategory.dailyShare,
        'description': dailyDescriptions[3],
        'images': ['assets/images/eat7.png'],
        'isVideo': false,
      },
      {
        'id': 'daily_share_5',
        'category': SubmissionCategory.dailyShare,
        'description': dailyDescriptions[4],
        'images': ['assets/images/eat8.png', 'assets/images/eat9.png'],
        'isVideo': false,
      },
      {
        'id': 'daily_share_6',
        'category': SubmissionCategory.dailyShare,
        'description': dailyDescriptions[5],
        'images': ['assets/images/eat10.png'],
        'isVideo': false,
      },
      {
        'id': 'daily_share_7',
        'category': SubmissionCategory.dailyShare,
        'description': dailyDescriptions[6],
        'images': ['assets/images/eat11.png'],
        'isVideo': false,
      },
    ];

    // 根据配置创建分享
    for (int i = 0; i < shareConfigs.length; i++) {
      final config = shareConfigs[i];
      // 确保用户 1001 (Johnson) 至少有前5条分享
      final user = i < 5 ? _getSpecificUser('1001') : _getRandomUser(random);

      final mediaAssets = await _createGroupMediaAssets(
        random,
        config['category'] == SubmissionCategory.challengeShare
            ? 'share'
            : 'eat',
        config['images'] as List<String>,
        isVideo: config['isVideo'] as bool,
        videoIndex: config['videoIndex'] as int?,
      );

      final appreciations = _createRandomAppreciations(random);

      final submission = ContentSubmission(
        submissionId: config['id'] as String,
        authorId: user['id']!,
        authorName: user['name']!,
        authorAvatar: user['avatar']!,
        category: config['category'] as SubmissionCategory,
        textDescription: config['description'] as String,
        mediaAssets: mediaAssets,
        associatedTask: null,
        appreciations: appreciations,
        appreciationCount: appreciations.length,
        publishedAt: DateTime.now().subtract(
          Duration(hours: random.nextInt(72)),
        ),
        lastModified: DateTime.now(),
      );

      defaultShares.add(submission);
    }

    for (final share in defaultShares) {
      await contentRepository.publishSubmission(share);
    }
  }

  Map<String, String> _getRandomUser(Random random) {
    final users = [
      {
        'id': '1001',
        'name': 'Johnson',
        'avatar': 'assets/images/avatar-one.png',
      },
      {'id': '1002', 'name': 'Emma', 'avatar': 'assets/images/avatar-two.png'},
      {
        'id': '1003',
        'name': 'Michael Chen',
        'avatar': 'assets/images/avatar-three.png',
      },
      {'id': '1004', 'name': 'John', 'avatar': 'assets/images/avatar-four.png'},
      {'id': '1005', 'name': 'Lily', 'avatar': 'assets/images/avatar-five.png'},
      {'id': '1006', 'name': 'Tom', 'avatar': 'assets/images/avatar-six.png'},
      {'id': '1007', 'name': 'Doe', 'avatar': 'assets/images/avatar-seven.png'},
      {
        'id': '1008',
        'name': 'Jane',
        'avatar': 'assets/images/avatar-eight.png',
      },
    ];
    return users[random.nextInt(users.length)];
  }

  // 获取指定用户信息
  Map<String, String> _getSpecificUser(String userId) {
    final users = [
      {
        'id': '1001',
        'name': 'Johnson',
        'avatar': 'assets/images/avatar-one.png',
      },
      {'id': '1002', 'name': 'Emma', 'avatar': 'assets/images/avatar-two.png'},
      {
        'id': '1003',
        'name': 'Michael Chen',
        'avatar': 'assets/images/avatar-three.png',
      },
      {'id': '1004', 'name': 'John', 'avatar': 'assets/images/avatar-four.png'},
      {'id': '1005', 'name': 'Lily', 'avatar': 'assets/images/avatar-five.png'},
      {'id': '1006', 'name': 'Tom', 'avatar': 'assets/images/avatar-six.png'},
      {'id': '1007', 'name': 'Doe', 'avatar': 'assets/images/avatar-seven.png'},
      {
        'id': '1008',
        'name': 'Jane',
        'avatar': 'assets/images/avatar-eight.png',
      },
    ];

    return users.firstWhere(
      (user) => user['id'] == userId,
      orElse: () => users[0], // 默认返回第一个用户
    );
  }

  Future<List<MediaAsset>> _createGroupMediaAssets(
    Random random,
    String type,
    List<String> assignedImages, {
    bool isVideo = false,
    int? videoIndex,
  }) async {
    if (isVideo) {
      final vIndex = videoIndex ?? (random.nextInt(4) + 1);
      final videoPath = 'assets/videos/share-video$vIndex.mp4';

      try {
        final videoData = await _processVideoAsset(videoPath, vIndex);

        return [
          MediaAsset(
            assetId: 'video_${DateTime.now().millisecondsSinceEpoch}',
            localPath: videoData['videoPath']!,
            mediaType: ContentMediaType.videoClip,
            thumbnailPath: videoData['thumbnailPath']!,
            uploadedAt: DateTime.now(),
          ),
        ];
      } catch (e) {
        return assignedImages
            .map(
              (imagePath) => MediaAsset(
                assetId:
                    'video_fallback_${DateTime.now().millisecondsSinceEpoch}_${assignedImages.indexOf(imagePath)}',
                localPath: imagePath,
                mediaType: ContentMediaType.imageCollection,
                thumbnailPath: null,
                uploadedAt: DateTime.now(),
              ),
            )
            .toList();
      }
    } else {
      // 对于图片类型，使用分配的图片组
      return assignedImages
          .map(
            (imagePath) => MediaAsset(
              assetId:
                  'img_${DateTime.now().millisecondsSinceEpoch}_${assignedImages.indexOf(imagePath)}',
              localPath: imagePath,
              mediaType: ContentMediaType.imageCollection,
              thumbnailPath: null,
              uploadedAt: DateTime.now(),
            ),
          )
          .toList();
    }
  }

  List<UserInteraction> _createRandomAppreciations(Random random) {
    final List<UserInteraction> appreciations = [];
    final appreciationCount = random.nextInt(15) + 1;

    final users = [
      {
        'id': '1001',
        'name': 'Johnson',
        'avatar': 'assets/images/avatar-one.png',
      },
      {'id': '1002', 'name': 'Emma', 'avatar': 'assets/images/avatar-two.png'},
      {
        'id': '1003',
        'name': 'Michael Chen',
        'avatar': 'assets/images/avatar-three.png',
      },
      {'id': '1004', 'name': 'John', 'avatar': 'assets/images/avatar-four.png'},
      {'id': '1005', 'name': 'Lily', 'avatar': 'assets/images/avatar-five.png'},
      {'id': '1006', 'name': 'Tom', 'avatar': 'assets/images/avatar-six.png'},
      {'id': '1007', 'name': 'Doe', 'avatar': 'assets/images/avatar-seven.png'},
      {
        'id': '1008',
        'name': 'Jane',
        'avatar': 'assets/images/avatar-eight.png',
      },
    ];

    final selectedUsers = <String>{};
    for (
      int i = 0;
      i < appreciationCount && selectedUsers.length < users.length;
      i++
    ) {
      final user = users[random.nextInt(users.length)];
      if (!selectedUsers.contains(user['id'])) {
        selectedUsers.add(user['id']!);

        appreciations.add(
          UserInteraction(
            interactionId: 'like_${DateTime.now().millisecondsSinceEpoch}_$i',
            userId: user['id']!,
            userName: user['name']!,
            userAvatar: user['avatar']!,
            interactedAt: DateTime.now().subtract(
              Duration(minutes: random.nextInt(1440)),
            ),
          ),
        );
      }
    }

    return appreciations;
  }

  Future<void> _initCommentsData() async {
    final localStore = LocalStore();
    final random = Random();

    final List<String> commentTemplates = [
      'Great job! Keep it up! 👏',
      'This is so inspiring! 💪',
      'Love your dedication to oral health! 🦷✨',
      'Amazing progress! 🌟',
      'You\'re doing fantastic! 😊',
      'This motivates me to do better too! 🙌',
      'Such a good habit to maintain! 👍',
      'Your smile must be so healthy! 😁',
      'Thanks for sharing this! 💫',
      'Keep up the excellent work! 🎯',
      'This is exactly what I needed to see today! ❤️',
      'Your consistency is admirable! 🏆',
      'Way to go! 🚀',
      'This is so helpful! Thank you! 🙏',
      'You\'re an inspiration! ✨',
      'Love seeing your progress! 📈',
      'Such dedication! 💯',
      'This made my day! ☀️',
      'Keep shining! 🌟',
      'Absolutely amazing! 🔥',
    ];

    final submissionIds = [
      ...List.generate(15, (i) => 'challenge_share_${i + 1}'),
      ...List.generate(14, (i) => 'daily_share_${i + 1}'),
    ];

    for (final submissionId in submissionIds) {
      final commentCount = random.nextInt(8) + 1;
      final List<Comment> comments = [];

      final users = [
        {
          'id': '1001',
          'name': 'Johnson',
          'avatar': 'assets/images/avatar-one.png',
        },
        {
          'id': '1002',
          'name': 'Emma',
          'avatar': 'assets/images/avatar-two.png',
        },
        {
          'id': '1003',
          'name': 'Michael Chen',
          'avatar': 'assets/images/avatar-three.png',
        },
        {
          'id': '1004',
          'name': 'John',
          'avatar': 'assets/images/avatar-four.png',
        },
        {
          'id': '1005',
          'name': 'Lily',
          'avatar': 'assets/images/avatar-five.png',
        },
        {'id': '1006', 'name': 'Tom', 'avatar': 'assets/images/avatar-six.png'},
        {
          'id': '1007',
          'name': 'Doe',
          'avatar': 'assets/images/avatar-seven.png',
        },
        {
          'id': '1008',
          'name': 'Jane',
          'avatar': 'assets/images/avatar-eight.png',
        },
      ];

      final selectedUsers = <String>{};
      for (
        int i = 0;
        i < commentCount && selectedUsers.length < users.length;
        i++
      ) {
        final user = users[random.nextInt(users.length)];
        if (!selectedUsers.contains(user['id'])) {
          selectedUsers.add(user['id']!);

          final comment = Comment(
            commentId: 'comment_${DateTime.now().millisecondsSinceEpoch}_$i',
            shareId: submissionId,
            userId: user['id']!,
            userName: user['name']!,
            userAvatar: user['avatar']!,
            content: commentTemplates[random.nextInt(commentTemplates.length)],
            createdAt: DateTime.now().subtract(
              Duration(minutes: random.nextInt(2880)), // 最多2天前
            ),
          );

          comments.add(comment);
        }
      }

      // 按时间排序（最新的在前）
      comments.sort((a, b) => b.createdAt.compareTo(a.createdAt));

      // 保存评论到本地存储
      final commentsJson = jsonEncode(comments.map((c) => c.toJson()).toList());
      await localStore.setTextValue('comments_$submissionId', commentsJson);
    }
  }

  Future<Map<String, String>> _processVideoAsset(
    String assetVideoPath,
    int videoIndex,
  ) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final videoDir = Directory('${directory.path}/videos');
      final thumbnailDir = Directory('${directory.path}/thumbnails');

      if (!await videoDir.exists()) {
        await videoDir.create(recursive: true);
      }
      if (!await thumbnailDir.exists()) {
        await thumbnailDir.create(recursive: true);
      }

      final localVideoPath = '${videoDir.path}/share_video$videoIndex.mp4';
      final thumbnailPath = '${thumbnailDir.path}/video${videoIndex}_thumb.jpg';

      final videoFile = File(localVideoPath);
      final thumbnailFile = File(thumbnailPath);

      if (await videoFile.exists() && await thumbnailFile.exists()) {
        return {'videoPath': localVideoPath, 'thumbnailPath': thumbnailPath};
      }

      if (!await videoFile.exists()) {
        final videoBytes = await rootBundle.load(assetVideoPath);
        await videoFile.writeAsBytes(videoBytes.buffer.asUint8List());
      }

      if (!await thumbnailFile.exists()) {
        final generatedThumbnailPath = await VideoThumbnail.thumbnailFile(
          video: localVideoPath,
          thumbnailPath: thumbnailDir.path,
          imageFormat: ImageFormat.JPEG,
          timeMs: 1000,
          quality: 75,
        );

        if (generatedThumbnailPath != null) {
          if (generatedThumbnailPath != thumbnailPath) {
            final generatedFile = File(generatedThumbnailPath);
            await generatedFile.copy(thumbnailPath);
            await generatedFile.delete();
          }
        } else {
          await _createFallbackThumbnail(videoIndex, thumbnailDir.path);
        }
      }

      return {'videoPath': localVideoPath, 'thumbnailPath': thumbnailPath};
    } catch (e) {
      throw Exception('Failed to process video asset: $e');
    }
  }

  Future<String> _createFallbackThumbnail(
    int videoIndex,
    String thumbnailDirPath,
  ) async {
    String sourceImagePath;
    switch (videoIndex) {
      case 1:
        sourceImagePath = 'assets/images/share3.png';
      case 2:
        sourceImagePath = 'assets/images/share4.png';
      case 3:
        sourceImagePath = 'assets/images/eat3.png';
      case 4:
        sourceImagePath = 'assets/images/eat4.png';
      default:
        sourceImagePath = 'assets/images/share1.png';
    }

    final imageBytes = await rootBundle.load(sourceImagePath);
    final thumbnailPath = '$thumbnailDirPath/video${videoIndex}_thumb.jpg';
    final thumbnailFile = File(thumbnailPath);
    await thumbnailFile.writeAsBytes(imageBytes.buffer.asUint8List());

    return thumbnailPath;
  }

  /// 初始化聊天数据
  Future<void> _initChatData() async {
    final chatData = ChatData();

    // 为 user007 (Johnson) 创建一些聊天会话和消息
    final user007Id = '1001'; // Johnson
    final user002Id = '1002'; // Emma
    final user003Id = '1003'; // Michael Chen
    final user004Id = '1004'; // John

    // 创建与 Emma 的会话
    final conv1 = await chatData.createConversation(user007Id, user002Id);

    // 添加一些消息
    await chatData.sendMessage(
      conversationId: conv1.id,
      senderId: user002Id,
      receiverId: user007Id,
      content: 'Hey Johnson! How\'s your dental practice going?',
      type: MessageType.text,
    );

    await Future.delayed(const Duration(milliseconds: 100));

    await chatData.sendMessage(
      conversationId: conv1.id,
      senderId: user007Id,
      receiverId: user002Id,
      content:
          'Hi Emma! It\'s been great. Just finished a complex root canal procedure today.',
      type: MessageType.text,
    );

    await Future.delayed(const Duration(milliseconds: 100));

    await chatData.sendMessage(
      conversationId: conv1.id,
      senderId: user002Id,
      receiverId: user007Id,
      content:
          'That sounds challenging! I\'ve been working on a dental health app design.',
      type: MessageType.text,
    );

    await Future.delayed(const Duration(milliseconds: 100));

    await chatData.sendMessage(
      conversationId: conv1.id,
      senderId: user007Id,
      receiverId: user002Id,
      content:
          'That\'s amazing! We definitely need better digital tools for patient education.',
      type: MessageType.text,
    );

    // 创建与 Michael Chen 的会话
    final conv2 = await chatData.createConversation(user007Id, user003Id);

    await chatData.sendMessage(
      conversationId: conv2.id,
      senderId: user003Id,
      receiverId: user007Id,
      content: 'Johnson, I need advice about teeth whitening procedures.',
      type: MessageType.text,
    );

    await Future.delayed(const Duration(milliseconds: 100));

    await chatData.sendMessage(
      conversationId: conv2.id,
      senderId: user007Id,
      receiverId: user003Id,
      content:
          'Sure! Professional whitening is much safer than over-the-counter options.',
      type: MessageType.text,
    );

    await Future.delayed(const Duration(milliseconds: 100));

    await chatData.sendMessage(
      conversationId: conv2.id,
      senderId: user003Id,
      receiverId: user007Id,
      content:
          'Great! Can you recommend the best treatment for sensitive teeth?',
      type: MessageType.text,
    );

    // 创建与 John 的会话
    final conv3 = await chatData.createConversation(user007Id, user004Id);

    await chatData.sendMessage(
      conversationId: conv3.id,
      senderId: user004Id,
      receiverId: user007Id,
      content: 'Hey, my kid is afraid of dental visits. Any tips?',
      type: MessageType.text,
    );

    await Future.delayed(const Duration(milliseconds: 100));

    await chatData.sendMessage(
      conversationId: conv3.id,
      senderId: user007Id,
      receiverId: user004Id,
      content:
          'Try explaining the process beforehand and bring their favorite toy!',
      type: MessageType.text,
    );

    await Future.delayed(const Duration(milliseconds: 100));

    await chatData.sendMessage(
      conversationId: conv3.id,
      senderId: user004Id,
      receiverId: user007Id,
      content:
          'That\'s helpful! Should we start with just a consultation visit first?',
      type: MessageType.text,
    );
  }
}
